<template>
  <view>
    <u-upload :width="step?'176':'80'" :height="step?'110':'80'" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="maxCount"></u-upload>
  </view>
</template> 
<script>
import {
  getToken,
} from "@/common/utils.js";
export default {
  props: {
    // fileList1: { // 当前选中的tab index
    //   type: Array,
    //   default: [] 
    // },
    step: {
      type: Boolean,
      default: false
    },
    uploadIndex: {
      type: Number,
      default: 0
    },
    maxCount: {
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      // action: $baseImgUrl,
      fileList1: [],
      file: []
    }
  },
  created() {
    // this.token = getToken()
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1)
      this.$emit('deleteHanlder', event.index)
    },
    // 新增图片
    async afterRead(event) {


      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this[`fileList${event.name}`].length
      lists.map((item) => {

        this[`fileList${event.name}`].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].thumb)

        this.file.push({
          url: this.$baseUrl + result.data,
          // id: result.id,
          size: lists[i].size,
          name: '附件' + (i + 1)

        })

        this.$emit('success', this.file, this.uploadIndex)
        let item = this[`fileList${event.name}`][fileListLen]
        this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '上传成功',
          url: result,

        }))
        fileListLen++
      }
    },
    uploadFilePromise(url) {
      const token = getToken()

      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: this.$baseImgUrl, // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'accept': 'application/json',
            'Authorization': 'Bearer' + ' ' + token //若有token，此处换上你的token，没有的话省略 
          },
          formData: {
            user: 'test'
          },
          success: (res) => {

            resolve(JSON.parse(res.data))
          }
        });
      })
    },
  }
}
</script>
<style lang="scss">
</style>